package com.example.wanbaqian.utils;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.example.wanbaqian.base.BaseListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.example.wanbaqian.activity.LoginActivity;
import com.example.wanbaqian.base.BaseApplication;
import com.example.wanbaqian.config.CommonValue;
import com.example.wanbaqian.base.HttpCallback;
import com.example.wanbaqian.config.HttpURL;
import com.example.wanbaqian.bean.Info;

import java.io.File;
import java.io.IOException;
import java.net.ConnectException;
import java.util.logging.Level;

import okhttp3.Call;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/4/15 0015.
 * 网络请求工具类
 */

public class HttpUtils {
    public static HttpUtils utils = null;
    private static final String TAG = "HttpUtils";
    private ProgressDialog dialog = null;

    public static HttpUtils getInstance() {
        if (null == utils) {
            synchronized (HttpUtils.class) {
                if (null == utils) {
                    utils = new HttpUtils();
                }
            }
        }
        return utils;
    }

    /**
     * post请求
     *
     * @param bodyContent 请求的内容 用于加密sign和请求参数
     * @param context
     * @param cacheKey    缓存的key 如果要设置不缓存key为空
     */
    public void post(String bodyContent, final Context context, String cacheKey, final int requestCode, final HttpCallback callback) {
        if (null == dialog) {
            dialog = new ProgressDialog(context);
        }
        dialog = dialog.show(context, "", "加载中...", false, true);
        dialog.setCanceledOnTouchOutside(false);

        bodyContent = StringUtils.nullToStrTrim(bodyContent);
//        Log.e(TAG, "参数post: "+bodyContent);
        OkGo.getInstance()
                .debug(TAG, Level.INFO, true)
                .setCacheMode(TextUtils.isEmpty(cacheKey) ? CacheMode.NO_CACHE : CacheMode.REQUEST_FAILED_READ_CACHE)
                .post(HttpURL.BASE_URL)
                .headers("reqlength", String.valueOf(StringUtils.getRealLength(bodyContent)))
                .headers("sign", StringUtils.encode(MD5Utils.md5(MD5Utils.md5(bodyContent) + SPUtils.getAccessKey(context))))
                .upJson(bodyContent)
                .cacheKey(cacheKey)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e(TAG, "onSuccess: 拿到数据"+s);
                        Info info = JsonUtils.getInstance().jsonToObjectk(JsonUtils.getInstance().getInfo(s), Info.class);
                        if (info.getCode().equals("100000")) {

                            callback.onSuccess(JsonUtils.getInstance().getContent(s), info, requestCode);
                        } else if (info.getCode().equals("110026")) {
                            Activity activity = (Activity) context;
                            Intent intent = new Intent(activity, LoginActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putInt("key", -1);
                            intent.putExtras(bundle);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            activity.startActivity(intent);
                            activity.finish();
                        } else {
                            callback.onError(info, requestCode);
                        }
//                        Log.e(TAG, "onSuccess: s=" + s);
//                        Log.e(TAG, "onSuccess: response=" + response);
                        dialog.dismiss();

                    }

                    @Override
                    public void onCacheSuccess(String s, Call call) {
                        dialog.dismiss();
                        callback.onSuccess(JsonUtils.getInstance().getContent(s),
                                JsonUtils.getInstance().jsonToObjectk(JsonUtils.getInstance().getInfo(s),
                                        Info.class), requestCode);
                        Log.i(TAG, "onCacheSuccess: " + s);
                        super.onCacheSuccess(s, call);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        if (e instanceof ConnectException) {
                            Toast.makeText(context, "请检查你的网络", Toast.LENGTH_SHORT).show();
                        }
                        dialog.dismiss();
                        Log.i(TAG, "onError:Exception= " + e);
                        Log.i(TAG, "onError:response=" + e);
                        super.onError(call, response, e);
                    }
                });
    }

    public void post(String bodyContent, String cacheKey, final int requestCode, final HttpCallback callback) {
//        post(bodyContent,BaseApplication.getInstance().context,cacheKey,requestCode,callback);

        bodyContent = StringUtils.nullToStrTrim(bodyContent);
        OkGo.getInstance()
                .debug(TAG, Level.INFO, true)
                .setCacheMode(TextUtils.isEmpty(cacheKey) ? CacheMode.NO_CACHE : CacheMode.REQUEST_FAILED_READ_CACHE)
                .post(HttpURL.BASE_URL)
                .headers("reqlength", String.valueOf(StringUtils.getRealLength(bodyContent)))
                .headers("sign", StringUtils.encode(MD5Utils.md5(MD5Utils.md5(bodyContent) + SPUtils.getAccessKey(BaseApplication.context))))
                .upJson(bodyContent)
                .cacheKey(cacheKey)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Info info = JsonUtils.getInstance().jsonToObjectk(JsonUtils.getInstance().getInfo(s), Info.class);
                        if (info.getCode().equals("100000")) {
                            callback.onSuccess(JsonUtils.getInstance().getContent(s), info, requestCode);
                        } else if (info.getCode().equals("110026")) {
                            callback.onError(info, requestCode);
                        } else {
                            callback.onError(info, requestCode);
                        }
                        Log.i(TAG, "onSuccess: s=" + s);
                        Log.i(TAG, "onSuccess: response=" + response);
                    }

                    @Override
                    public void onCacheSuccess(String s, Call call) {
                        callback.onSuccess(JsonUtils.getInstance().getContent(s),
                                JsonUtils.getInstance().jsonToObjectk(JsonUtils.getInstance().getInfo(s),
                                        Info.class), requestCode);
                        Log.i(TAG, "onCacheSuccess: " + s);
                        super.onCacheSuccess(s, call);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        if (e instanceof ConnectException) {
                            Toast.makeText(BaseApplication.context, "请检查你的网络", Toast.LENGTH_SHORT).show();
                        }
                        Log.i(TAG, "onError:Exception= " + e);
                        Log.i(TAG, "onError:response=" + e);
                        super.onError(call, response, e);
                    }
                });

    }

    /**
     * post发送文件
     *
     * @param context
     */
    public void postFile(String action, final Context context, final String pic_type, File file, final int requestCode, final HttpCallback callback) {
        String time = TimeUtils.getCurrentTimeByFormat();
        String reqlength = file.length() + "";
        String reqcontentmd5 = MD5Utils.md5file(file);
        Log.i(TAG, "postFile: " + action + "\n" + SPUtils.getAccessid(context) + "\n" + time + "\n" + reqlength + "\n" + reqcontentmd5);
        if (null == dialog) {
            dialog = new ProgressDialog(context);
        }
        dialog = dialog.show(context, "", "图片文件较大,请耐心等候...", false, false);
        dialog.setCanceledOnTouchOutside(false);

        OkGo.getInstance()
                .debug(TAG, Level.INFO, true)
                .post(HttpURL.BASE_URL)
                .headers("accessid", SPUtils.getAccessid(context))
                .headers("action", action)
                .headers("version", BaseUtils.geVersionCode(context))
                .headers("device_port", "android")
                .headers("sign", StringUtils.encode(MD5Utils.md5(MD5Utils.md5(action + "\n" + SPUtils.getAccessid(context) + "\n" + time + "\n" + reqlength + "\n" + reqcontentmd5) + SPUtils.getAccessKey(context))))
                .headers("trackid", "android")
                .headers("ip", NetWorkUtils.getIPAddress(context))
                .headers("reqtime", time)
                .headers("reqlength", reqlength)
                .headers("reqcontentmd5", reqcontentmd5)
                .headers("pictype", pic_type)
                .requestBody(RequestBody.create(null, file))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        dialog.dismiss();
                        Info info = JsonUtils.getInstance().jsonToObjectk(JsonUtils.getInstance().getInfo(s), Info.class);
                        if (info.getCode().equals("100000")) {
                            callback.onSuccess(JsonUtils.getInstance().getContent(s), info, requestCode);
                        } else if (info.getCode().equals("110026")) {
                            Activity activity = (Activity) context;
                            Intent intent = new Intent(activity, LoginActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putInt("key", -1);
                            intent.putExtras(bundle);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            activity.startActivity(intent);
                            activity.finish();
                        } else {
                            callback.onError(info, requestCode);
                        }
                        Log.i(TAG, "onSuccess: " + s);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        dialog.dismiss();
                        if (e instanceof ConnectException) {
                            Toast.makeText(BaseApplication.context, "请检查你的网络", Toast.LENGTH_SHORT).show();
                        }
                        super.onError(call, response, e);
//                        Log.i(TAG, "onSuccess: " + response.message());
                    }
                });
    }

    /**
     * post请求当通行证失败的时候
     *
     * @param bodyContent 请求的内容 用于加密sign和请求参数
     * @param context
     */
    public void postKey(String bodyContent, final Context context, final int requestCode, final HttpCallback callback) {
        if (null == dialog) {
            dialog = new ProgressDialog(context);
        }
        dialog = dialog.show(context, "", "加载中...", false, true);
        dialog.setCanceledOnTouchOutside(false);

        bodyContent = StringUtils.nullToStrTrim(bodyContent);

//        Log.e("postKey", "postKey: "+System.currentTimeMillis());
        Log.e("postKey", "reqlength: "+String.valueOf(StringUtils.getRealLength(bodyContent)));
        Log.e("postKey", "sign: "+StringUtils.encode(MD5Utils.md5(MD5Utils.md5(bodyContent) + CommonValue.accessKey_value)));
        Log.e("postKey", "bodyContent: "+bodyContent);
        OkGo.getInstance()
                .debug(TAG, Level.INFO, true)
                .post(HttpURL.BASE_URL)
                .headers("reqlength", String.valueOf(StringUtils.getRealLength(bodyContent)))
                .headers("sign", StringUtils.encode(MD5Utils.md5(MD5Utils.md5(bodyContent) + CommonValue.accessKey_value)))
                .upJson(bodyContent)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                        Info info = JsonUtils.getInstance().jsonToObjectk(JsonUtils.getInstance().getInfo(s), Info.class);
                        if (info.getCode().equals("100000")) {
                            callback.onSuccess(JsonUtils.getInstance().getContent(s), info, requestCode);
                        } else {
                            callback.onError(info, requestCode);
                        }
                        Log.i(TAG, "onSuccess: s=" + s);
                        Log.i(TAG, "onSuccess: response=" + response);
                        dialog.dismiss();
//                        Log.e("LOGIN_SU", "dismiss: "+System.currentTimeMillis());
                    }

                    @Override
                    public void onCacheSuccess(String s, Call call) {
                        dialog.dismiss();
                        callback.onSuccess(JsonUtils.getInstance().getContent(s),
                                JsonUtils.getInstance().jsonToObjectk(JsonUtils.getInstance().getInfo(s),
                                        Info.class), requestCode);
                        Log.i(TAG, "onCacheSuccess: " + s);
                        super.onCacheSuccess(s, call);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        if (e instanceof ConnectException) {
                            Toast.makeText(context, "请检查你的网络", Toast.LENGTH_SHORT).show();
                        }
                        dialog.dismiss();
                        Log.i(TAG, "onError:Exception= " + e);
                        Log.i(TAG, "onError:response=" + e);
                        super.onError(call, response, e);
                    }
                });
    }

    public void downFile(String url, String fileName, final BaseListener listener){
        OkGo.getInstance()
                .debug(TAG, Level.INFO, true)
                .get(url)
                .execute(new FileCallback(fileName) {
                    @Override
                    public void onSuccess(File file, Call call, Response response) {
                        String path = file.getPath();
                        Log.e("WebView", "onSuccess: "+path);
                        listener.downFileSuccess(file);
                    }
                });
    }
}
